package icraf.carbon.gui;

import static icraf.carbon.gui.MenuFactory.MenuProperty.PROJECT_ZONATION;
import icraf.carbon.core.Project;
import icraf.carbon.gui.MenuFactory.MenuProperty;

import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;

import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.table.TableModel;

public class InputTransitionMatrix extends LCMatrixTabPanel {
	public class Listener implements PropertyChangeListener, ActionListener {

		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			updateTime();
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			if (MenuProperty.LIST_IMPORT_CLIPBOARD.isAction(e)) {
				clipboardPanel.updateClipboardData();
				JDialog d = clipboardPanel.createDialog((Window)getSelectedPanel().getRootPane().getParent(), ModalityType.APPLICATION_MODAL);
				Point loc = getSelectedPanel().getRootPane().getLocationOnScreen();
				d.setLocation(loc.x, loc.y);
				d.setVisible(true);
				if (clipboardPanel.isImport()) {
					importFromClipboard();
				}
			} else if (MenuProperty.INPUT_RESET.isAction(e)) {
				int opt = JOptionPane.showConfirmDialog((Component)e.getSource(), MenuProperty.INPUT_RESET_CONFIRM.getAccessibleDescription(),
						MenuProperty.INPUT_RESET_CONFIRM.getLabel(), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
				if(opt == JOptionPane.OK_OPTION) {
					resetValue();
				}
			}
		}

	}

	private static final long serialVersionUID = 4305939712235366956L;
	private Listener listener = new Listener();
	private LCClipboardPanel clipboardPanel = new LCClipboardPanel();
	private JFormattedTextField projectTime;
	private ProjectTreePanel projectTreePanel;
	private DecimalFormat formatter = (DecimalFormat) NumberFormat
			.getNumberInstance();
	
	public InputTransitionMatrix(ProjectTreePanel projectDock) {
		projectTreePanel = projectDock;
		projectTime = new JFormattedTextField();
		projectTime.setValue(new Integer(0));
		projectTime.setColumns(10);
		projectTime.addPropertyChangeListener(listener);
		projectTime.setMaximumSize(new Dimension(50, 20));

		//JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
		JToolBar p = new JToolBar();
		
		p.setFloatable(false);
		p.add(new JLabel(MenuProperty.INPUT_TIME.getLabel()+":"));
		p.add(projectTime);
		p.addSeparator(new Dimension(50, 20));
		p.add(MenuFactory.createButtonIcon(MenuProperty.LIST_IMPORT_CLIPBOARD, listener));
		p.addSeparator(new Dimension(50, 20));
		p.add(MenuFactory.createButton(MenuProperty.INPUT_RESET, listener, true, null));
		setTopComponent(p);
		
		clipboardPanel.setPreferredSize(new Dimension(600, 400));
	}

	private boolean checkAreaSize() {
//		cek zone area fraction
		MatrixPanel p = getSelectedPanel();
		LCTableModel m = (LCTableModel)p.getMatrixTableModel();
		if(m.getValueScale() == 0 ||m.getProject().getZoneList().get(m.getZoneIndex()).getAreaSize()==0) {
			if(p.isSelectUnitArea()) {
				int opt = JOptionPane
						.showConfirmDialog(
								this,
								MenuProperty.PROJECT_ZONE_MATRIX_AREA_ERROR.getAccessibleDescription(),
								MenuProperty.PROJECT_ZONE_MATRIX_AREA_ERROR.getLabel(),
								JOptionPane.YES_NO_OPTION);
				if (opt == JOptionPane.NO_OPTION) {
					projectTreePanel.setSelection(getProject(), PROJECT_ZONATION);
					return false;
				} else {
					
					double sum = 0;
					if(clipboardPanel.isLCClipboard()) {
						TableModel tm = clipboardPanel.getLcTableModel();
						for(int r = 0; r < tm.getRowCount(); r++) {
							for(int c = 0; c < tm.getColumnCount(); c++) {
								if(tm.getValueAt(r, c) == null) continue;
								sum += ((Double) tm.getValueAt(r, c)).doubleValue() ;
							}
						}
					} else {
						String[][] strData = clipboardPanel.getData();
						if(strData == null) return false;
						for(int r = 0; r < strData.length; r++) {
							for(int c = 0; c < strData[r].length; c++) {
								if(r < m.getRowCount() && c < m.getColumnCount())
									try {
										strData[r][c] = strData[r][c].replaceAll( "[^\\d.,-Ee]", "" );
										sum += formatter.parse(strData[r][c].trim()).doubleValue();
									} catch (ParseException e) {
									}
							}
						}
					}
					
					Project prj = getProject();
					double areaArr[] = new double[prj.getNumberOfZone()];
					for (int i = 0; i < prj.getNumberOfZone(); i++) {
						double frac = prj.getZoneList().get(i).getAreaFraction();
						areaArr[i] = frac * prj.getTotalArea();
					}
					prj.setTotalArea(prj.getTotalArea() + sum);
					areaArr[m.getZoneIndex()] = sum;
					for (int i = 0; i < prj.getNumberOfZone(); i++) {
						prj.getZoneList().get(i).setAreaRatio(areaArr[i] /prj.getTotalArea());
					}
					p.setSelectUnitArea(true);
				}
			} else {
				int opt = JOptionPane
						.showConfirmDialog(
								this,
								MenuProperty.PROJECT_ZONE_MATRIX_FRACTION_ERROR.getAccessibleDescription(),
								MenuProperty.PROJECT_ZONE_MATRIX_FRACTION_ERROR.getLabel(),
								JOptionPane.YES_NO_OPTION);
				if (opt == JOptionPane.NO_OPTION) {
					projectTreePanel.setSelection(getProject(), PROJECT_ZONATION);
				} else {
					p.setSelectUnitArea(true);
				}
				return false;
			}
		}
		return true;
	}
	
	private void importFromClipboard() {
		if(!checkAreaSize()) {
			return;
		}
		MatrixPanel p = getSelectedPanel();
		LCTableModel m = (LCTableModel)p.getMatrixTableModel();
		if(clipboardPanel.isLCClipboard()) {
			
			TableModel tm = clipboardPanel.getLcTableModel();
			for(int r = 0; r < tm.getRowCount(); r++) {
				for(int c = 0; c < tm.getColumnCount(); c++) {
					m.setValueAt(tm.getValueAt(r, c), r, c);
				}
			}

		} else {
			
			String[][] strData = clipboardPanel.getData();
			if(strData == null) return;
			for(int r = 0; r < strData.length; r++) {
				for(int c = 0; c < strData[r].length; c++) {
					if(r < m.getRowCount() && c < m.getColumnCount())
						m.setValueAt(strData[r][c], r, c);
				}
			}
		}
		
	}

	@Override
	public void setProject(Project project) {
		super.setProject(project);
		setNegativeAllowed(false);
		projectTime.setText(Integer.toString((int) getProject()
				.getDurationTime()));
		clipboardPanel.setProject(project);
	}

	private void updateTime() {
		if(getProject() == null) return;
		int d = ((Number)projectTime.getValue()).intValue();
		getProject().setTime(d);
		
	}
	
	

}
